package cc.iits.demo.crane.web.support;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;

import java.util.Date;

/**
 * 字符串转换时间
 */
public class StringToDateConverter implements Converter<String, Date> {

    private final static String DATE_SPLIT="-";
    private final static String DATETIME_SPLIT=":";
    private final static String DATETIME_REGEX="^\\d+$";

    @Nullable
    @Override
    public Date convert(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        source = source.trim();
        try {
            if (source.contains("-")) {
                if (source.contains(":")) {
                    return DateUtils.parseDate(source, Constants.DATETIME_PATTERN);
                } else {
                    return DateUtils.parseDate(source, Constants.DATE_PATTERN);
                }
            } else if (source.matches("^\\d+$")) {
                Long lDate = new Long(source);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", source));
    }
}
